// 引入koa-router
const Router = require('koa2-router');
const router = new Router();
const sql = require('../../config/config');
// 引入jsonwebtoken模块
const jwt = require("jsonwebtoken");
const SECRET = "hello";
//收货地址
router.get('/addressAdministration',async (ctx)=>{
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    //查询addressAdministration表
    let addressAdministration
    addressAdministration = await sql('select * from addressAdministration where user_id = ?',[decoded.ID]);
    //添加地址
    let site = ctx.request.query;
    if (site.codeAdd==='200'){
        //解构赋值
        let {name,phone,address,addressProvince,addressCity,addressDistrict,addressDefaultAddress,tacitlyApprove} = site;
        //当前为默认清空
        if (Boolean(tacitlyApprove)){
            await sql('update addressAdministration set tacitlyApprove = 0 where tacitlyApprove = 1 and user_id = ?',[decoded.ID])
        }
        //添加到数据库
        await sql(`insert into addressAdministration value(null,?,?,?,?,?,?,?,?,?)`,[decoded.ID,name,phone,addressProvince,addressCity,addressDistrict,addressDefaultAddress,tacitlyApprove,address]);
        addressAdministration = await sql('select * from addressAdministration where user_id = ?',[decoded.ID]);
    }else if (site.codeRemove==='300'){
        //删除数据库中的数据
        await sql(`delete from addressAdministration where id = ${site.id} and user_id = ${decoded.ID}`)
    }else if (site.codeModification==='400'){
        //解构赋值
        let {name,phone,address,addressProvince,addressCity,addressDistrict,addressDefaultAddress,tacitlyApprove} = site;
        if (Boolean(tacitlyApprove)){
            await sql('update addressAdministration set tacitlyApprove = 0 where tacitlyApprove = 1 and user_id = ?',[decoded.ID]);
        }
        //添加到数据库
        await sql(`update addressAdministration set name=?,phone=?,addressProvince=?,addressCity=?,addressDistrict=?,addressDefaultAddress=?,tacitlyApprove=?,address=? where id = ${site.id} and user_id = ${decoded.ID}`,[name,phone,addressProvince,addressCity,addressDistrict,addressDefaultAddress,tacitlyApprove,address]);
    }
    ctx.body = addressAdministration;
});
//图片
router.get('/pic',async (ctx)=>{
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    let pic = await sql(`select oldPapers from user where id = ${decoded.ID}`);
    ctx.body = pic;
});
//修改密码
router.post('/pwd',async (ctx)=>{
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    //数据库查询旧密码
    let password = await sql('select password from user where id = ?',[decoded.ID]);
    //解密密码
    let oldPassword = jwt.verify(password[0].password, SECRET);
    // console.log(ctx.request.body)
    if (ctx.request.body.code===200){
        let newPassword = ctx.request.body.newPassword;
        // 密码加密
        const encryptionPwd = jwt.sign(newPassword, SECRET);
        await sql('update user set password = ?,isLogin = 0 where id = ?',[encryptionPwd,decoded.ID]);
    }
    //发送旧密码
    ctx.body = oldPassword;
});
//用户开始界面
router.get('/user',async (ctx)=>{
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    //查询当前登录的账号
    const user = await sql('select * from user where id = ?',[decoded.ID]);
    ctx.body = user;
});
//用户订单
router.get('/order',async (ctx)=>{
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    //查询
    let order;
    order = await sql('select * from orders where userid = ?',[decoded.ID]);
    //获取前端传来的值
    const {orderid,code} = ctx.request.query;
    //是remove就删除
    // if (code==='remove'){
    //     await sql('delete from orders where orderid = ? and userid = ?',[orderid,decoded.ID]);
    //     order = '删除成功'
    // }
    //cancel取消
    if (code==='cancel'){
        await sql('update orders set status = 4 where orderid = ? and userid = ?',[orderid,decoded.ID]);
        // order = '删除成功'
    }
    //发送回前端
    ctx.body = order;
})
//订单超时
router.post('/order',async (ctx)=>{
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    //查询
    let order = await sql('select * from orders where userid = ? and status = 1',[decoded.ID]);
    //处理超时
    order.forEach(async (item)=>{
        let oldDate = new Date(item.paymenttime);
        let newDate = new Date();
        // console.log((newDate - oldDate)/1000/60/60);
        //判断是否超时
        if ((newDate - oldDate)/1000/60/60>1){
            //超时将当前遍历的数据状态改为1
            await sql('update orders set status = 4 where orderid = ?',[item.orderid]);
        }
    })
    //查询
    // let timeOut = await sql('select * from orders where userid = ? and orderid = 1',[decoded.ID]);
    // await sql('update orders set status = 4 where orderid = ? and userid = ?',[orderid,decoded.ID]);
    //发送回前端
    ctx.body = order;
})
//订单详情
router.get('/orderDetails',async (ctx)=>{
    //订单编号
    const orderNumber = ctx.request.query.orderNumber;
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    //查询当前订单详情
    let order = await sql('select * from orders where userid = ? and orderid = ?',[decoded.ID,orderNumber])
    //获取前端传来的值
    const {orderid,code} = ctx.request.query;
    //是remove就删除
    if (code==='remove'){
        await sql('delete from orders where orderid = ? and userid = ?',[orderid,decoded.ID]);
        order = '删除成功'
    }
    if (code==='address'){
        let { recipients,phone,province,city,district,defaultAddress} = ctx.request.query;
        await sql('update orders set name=?,phone=?,addressProvince=?,addressCity=?,addressDistrict=?,addressDefaultAddress=?',[recipients,phone,province,city,district,defaultAddress])
    }
    //发送回前端
    ctx.body = order;
})
//收藏
router.get('/collection',async (ctx)=>{
    //获取token
    const token = ctx.request.headers.authorization;
    //解密token
    let decoded = jwt.verify(token, SECRET);
    let remove;
    let collection;
    //获取收藏数据并且state为1
    collection = await sql(
        `select * from collection 
        join product on collection.proid = product.id
        where userid = ? and state = 1 `
        ,[decoded.ID]);
    //获取前端发送的值 解构
    let {code,collid}=ctx.request.query
    //删除
    if (code==='remove'){
        await sql('delete from collection where collid = ?',[collid]);
        remove='删除成功';
        collection = await sql(
            `select * from collection 
        join product on collection.proid = product.id
        where userid = ? and state = 1 `
            ,[decoded.ID]);
    }
    //返回前端 将商品返回
    ctx.body = {collection,remove};
})
//暴露
module.exports = router;